from time import sleep

from redis import ConnectionPool, StrictRedis


class RedisClientRemote(object):

    def __init__(self, db):
        self.db = db
        self.pool = ConnectionPool(**{
            'host': '111.173.119.79',
            'port': 6379,
            'db': self.db,
            'password': 950218
        })
        self.client = StrictRedis(connection_pool=self.pool)

    def reConnect(self):
        try:
            self.client.ping()
        except:
            self.client = StrictRedis(connection_pool=self.pool)

    def popReport(self):
        report = self.client.rpop('report_dev')
        if report:
            return str(report, encoding='utf-8')
        return None

    def popSuggest(self):
        suggest = self.client.rpop('suggest')
        if suggest:
            return str(suggest, encoding='utf-8')
        return None


class RedisClientTencent(object):

    def __init__(self):
        self.pool = ConnectionPool(**{
            'host': '129.211.169.177',
            'port': 6379,
            'db': 0,
            'password': 950218
        })
        self.client = StrictRedis(connection_pool=self.pool)

    def reConnect(self):
        try:
            self.client.ping()
        except:
            self.client = StrictRedis(connection_pool=self.pool)

    def pushReport(self, report):
        self.reConnect()
        self.client.rpush('report_dev', report)

    def pushSuggest(self, suggest):
        self.reConnect()
        self.client.rpush('suggest', suggest)


if __name__ == '__main__':
    local = RedisClientTencent()
    remote = RedisClientRemote(0)
    while True:
        while True:
            suggest = remote.popSuggest()
            if suggest:
                local.pushSuggest(suggest)
            else:
                break
        report = remote.popReport()
        if report:
            local.pushReport(report)
        sleep(5)
